/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FuRmPanel.java
 *
 * Created on 29/11/2011, 21:45:34
 */

package proj5labbd.graphics.funcionario;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

public class FuRmPanel extends OperationPanel {

    /** Creates new form FuRmPanel */
    public FuRmPanel(FuncionarioFrame frame, DBInterface dbInterface) {
        super(frame,dbInterface);
        initComponents();
        jbtRemove.addActionListener(new FuncionarioAction());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jtbRemove = new javax.swing.JTable();
        jbtRemove = new javax.swing.JButton();
        jpnInsert = new javax.swing.JPanel();
        jlbCPF = new javax.swing.JLabel();
        jftxtCPF = new javax.swing.JFormattedTextField();
        jlbNome = new javax.swing.JLabel();
        jtxtNome = new javax.swing.JTextField();
        jlbDate = new javax.swing.JLabel();
        jlbSalario = new javax.swing.JLabel();
        jtxtSalario = new javax.swing.JTextField();
        jlbTipo = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtbTipoFu = new javax.swing.JTable();
        jftxtDate = new javax.swing.JFormattedTextField();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Remoção"));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jtbRemove.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jtbRemove.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jtbRemove);

        jbtRemove.setText("Remover");

        jpnInsert.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros de remoção"));

        jlbCPF.setText("CPF");

        try {
            jftxtCPF.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtCPF.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        jlbNome.setText("Nome Completo");

        jlbDate.setText("Data de nascimento");

        jlbSalario.setText("Salário");

        jlbTipo.setText("Tipo de funcionário");

        jtbTipoFu.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jtbTipoFu.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jtbTipoFu.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jtbTipoFuFocusLost(evt);
            }
        });
        jScrollPane2.setViewportView(jtbTipoFu);

        try {
            jftxtDate.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        javax.swing.GroupLayout jpnInsertLayout = new javax.swing.GroupLayout(jpnInsert);
        jpnInsert.setLayout(jpnInsertLayout);
        jpnInsertLayout.setHorizontalGroup(
            jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnInsertLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jlbTipo)
                    .addGroup(jpnInsertLayout.createSequentialGroup()
                        .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jlbCPF, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jftxtCPF, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 205, Short.MAX_VALUE)
                            .addComponent(jtxtNome, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlbNome, javax.swing.GroupLayout.Alignment.LEADING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jftxtDate)
                            .addComponent(jlbDate)
                            .addComponent(jlbSalario, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE)
                            .addComponent(jtxtSalario))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jpnInsertLayout.setVerticalGroup(
            jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnInsertLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbCPF)
                    .addComponent(jlbDate))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jftxtCPF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jftxtDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbNome)
                    .addComponent(jlbSalario))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtxtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jtxtSalario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jlbTipo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jpnInsert, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jScrollPane1, 0, 0, Short.MAX_VALUE))
                        .addContainerGap())
                    .addComponent(jbtRemove, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpnInsert, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jbtRemove))
        );
    }// </editor-fold>//GEN-END:initComponents

    /*
     * Resgata as informações das tabelas que serão exibidas
     */
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        try {
            // TODO add your handling code here:
            setupTable();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível resgatar as informações das tabelas.");
            frame.printException(ex);
        }
    }//GEN-LAST:event_formComponentShown

    private void jtbTipoFuFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtbTipoFuFocusLost
        // TODO add your handling code here:
        
    }//GEN-LAST:event_jtbTipoFuFocusLost

    /*
     * Trata os eventos do mouse
     */
    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        // TODO add your handling code here:
        jtbTipoFu.clearSelection();
        jtbRemove.clearSelection();
    }//GEN-LAST:event_formMouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton jbtRemove;
    private javax.swing.JFormattedTextField jftxtCPF;
    private javax.swing.JFormattedTextField jftxtDate;
    private javax.swing.JLabel jlbCPF;
    private javax.swing.JLabel jlbDate;
    private javax.swing.JLabel jlbNome;
    private javax.swing.JLabel jlbSalario;
    private javax.swing.JLabel jlbTipo;
    private javax.swing.JPanel jpnInsert;
    private javax.swing.JTable jtbRemove;
    private javax.swing.JTable jtbTipoFu;
    private javax.swing.JTextField jtxtNome;
    private javax.swing.JTextField jtxtSalario;
    // End of variables declaration//GEN-END:variables

    /*
     * Formata a tabela funcionario
     */
    public void setupTable() throws SQLException {

        String [] titlesDe = {"ID","Nome","Data de nascimento","CPF","Salario","Carreira"};
        String [] fieldsDe= {"funcionario.idFu","funcionario.nomeCompletoFu","funcionario.dataNascimentoFu",
            "funcionario.cpfFu","funcionario.salarioFu","tipoFuncionario.descricaoTipoFu"
        };
        String [] paramsDe = {"funcionario.idTipoFu=tipoFuncionario.idTipoFu"};
        String [][] result = dbInterface.view(fieldsDe,paramsDe,new String[]{"funcionario","tipoFuncionario"});

        String [] titlesTipo = {"ID","Salario","Tipo"};

        DefaultTableModel model = new DefaultTableModel(result,titlesDe);
        jtbRemove.setModel(model);

        result = dbInterface.view(null, null, new String[]{"tipoFuncionario"});
        model = new DefaultTableModel(result,titlesTipo);
        jtbTipoFu.setModel(model);

    }

    class FuncionarioAction implements ActionListener {
        
        /*
         * Controla os eventos de atualização
         */
        public void actionPerformed(ActionEvent e) {
            ArrayList<String> param = new ArrayList<String>();

                if (jtxtNome.getText().trim().compareTo("") != 0) {
                    param.add("UPPER(funcionario.nomeCompletoDe)=UPPER('"+jtxtNome.getText()+"')");
                }
                if (jftxtCPF.getText().compareTo("   .   .   -  ") != 0) {
                    param.add("funcionario.cpfFu='"+jftxtCPF.getText()+"'");
                }
                if (jftxtDate.getText().compareTo("  -  -    ") != 0) {
                    param.add("funcionario.dataNascimentoFu="+"TO_DATE('"+jftxtDate.getText()+"','DD-MM-YYYY')");
                }
                if (jtxtSalario.getText().trim().compareTo("") != 0) {
                    param.add("salarioFu="+jtxtSalario.getText());
                }

                if (jtbTipoFu.getSelectedRowCount() == 1) {
                    param.add((String)jtbTipoFu.getValueAt(jtbTipoFu.getSelectedRow(),0));
                }

                if (param.size() > 0) {
                    try {
                        String[] paramArray = new String[param.size()];
                        param.toArray(paramArray);
                        dbInterface.remove(paramArray, new String[]{"funcionario"});
                    } catch (SQLException ex) {
                        frame.printException(ex);
                        JOptionPane.showMessageDialog(null, "Erro ao remover as tuplas desejadas.");
                    }
                } else {

                    if (jtbRemove.getSelectedRowCount() > 1) {
                    JOptionPane.showMessageDialog(null, "Você deve selecionar apenas uma linha da tabela.");
                    }
                    else if (jtbRemove.getSelectedRowCount() == 1) {
                        try {
                            String[] params = new String[1];
                            params[0] = "idFu=" + jtbRemove.getValueAt(jtbRemove.getSelectedRow(), 0);
                            dbInterface.remove(params, new String[]{"funcionario"});
                        } catch (SQLException ex) {
                            frame.printException(ex);
                            JOptionPane.showMessageDialog(null, "Erro ao tentar remover a tupla.");
                        }
                    }
                    else if (jtbRemove.getSelectedRowCount() == 0) {
                        JOptionPane.showMessageDialog(null, "Você deve escolhar uma tupla ou um parâmetro para a remoção.");
                    }
                }
                
            try {
                setupTable();
            } catch (SQLException ex) {
                frame.printException(ex);
            }

        }
    }

}
